package org.xshop.socket;

import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.Assert;
import org.xshop.model.TExpressman;
import org.xshop.service.ITExpressmanService;

import com.alibaba.fastjson.JSON;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import top.ibase4j.core.util.InstanceUtil;

public class ServerHandler extends SimpleChannelInboundHandler<String> {
    private final Logger logger = LogManager.getLogger(getClass());
    private ITExpressmanService expressmanService;
    private Map<String, Long> expressmans = InstanceUtil.newHashMap();

    public ServerHandler(ITExpressmanService expressmanService) {
        this.expressmanService = expressmanService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String ip = channel.remoteAddress().toString().substring(1);
        logger.warn("The connection of client [{}] is active.", ip);
        ctx.writeAndFlush("0");
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void channelRead0(ChannelHandlerContext ctx, String body) throws Exception {
        Channel channel = ctx.channel();
        String ip = channel.remoteAddress().toString().substring(1);
        String msg = String.valueOf(body);
        logger.info("Client [{}], Request [{}]..........", ip, msg); // 打印收到的信息

        //
        String rsp = "99";
        try {
            Map<String, Object> params = JSON.parseObject(msg, Map.class);
            String type = String.valueOf(params.get("type"));
            if ("1".equalsIgnoreCase(type)) {
                Assert.notNull(params.get("id"), "骑手id不能为空");
                Assert.notNull(params.get("lon"), "经度不能为空");
                Assert.notNull(params.get("lat"), "纬度不能为空");
                TExpressman expressman = InstanceUtil.transMap2Bean(params, TExpressman.class);
                expressman.setIsOnline(1);
                expressmanService.update(expressman);
                expressmans.put(ip, expressman.getId());
                rsp = "1";
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        ctx.writeAndFlush(rsp);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        try {
            Channel channel = ctx.channel();
            String ip = channel.remoteAddress().toString().substring(1);
            logger.warn("The connection of client [{}] is closed.", ip);
            if (expressmans.get(ip) != null) {
                TExpressman expressman = new TExpressman();
                expressman.setId(expressmans.get(ip));
                expressman.setIsOnline(0);
                expressmanService.update(expressman);
            }
            channel.close();
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        String ip = channel.remoteAddress().toString().substring(1);
        logger.error(ip, cause);
    }
}
